#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：python_learning 
@File ：socket同一条通路收发信息.py
@IDE  ：PyCharm 
@Author ：李涵彬
@Date ：2024/12/29 13:14 
"""

import socket
from queue import Queue
import threading


class Communication:
	def __init__(self, host, port):
		self.host = host
		self.port = port
		self.message_queue = Queue()
		self.running = True

	def start_sender(self):
		threading.Thread(target=self._send, args=()).start()

	def start_receiver(self):
		threading.Thread(target=self._receive, args=()).start()

	def _send(self):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
			s.connect((self.host, self.port))
			while self.running:
				message = self.message_queue.get()
				s.sendall(message.encode())
				print(f"发送：{message}")
				s.recv(1024)  # 等待接收确认报文
				print("接收到确认报文。")
				self.message_queue.task_done()

	def _receive(self):
		with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
			s.bind((self.host, self.port))
			s.listen()
			conn, addr = s.accept()
			with conn:
				print(f"连接地址：{addr}")
				while self.running:
					data = conn.recv(1024)
					if not data:
						break
					print(f"接收：{data.decode()}")
					conn.sendall("确认收到".encode())


# 使用
if __name__ == "__main__":
	comm = Communication('localhost', 12345)
	comm.start_sender()
	comm.start_receiver()
	comm.message_queue.put("Hello, Server!")
